package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.dto.PageResult;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.MyCourseTableParams;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: Hes
 * @description 选课学习实现
 * @date: 2023/6/27 10:12
 */
@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {

    @Autowired
    MyCourseTablesServiceImpl currentPorxy;
    @Autowired
    ContentServiceClient contentServiceClient;

    @Autowired
    XcChooseCourseMapper xcChooseCourseMapper;

    @Autowired
    XcCourseTablesMapper xcCourseTablesMapper;

    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {
        //查询课程信息
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null) {
            XueChengPlusException.cast("内容管理远程调用服务熔断");
        }
        //查询收费规则
        String charge = coursepublish.getCharge();
        //选课记录
        XcChooseCourse chooseCourse = new XcChooseCourse();
        //免费课程直接添加学科记录和我的课程表
        if ("201000".equals(charge)) {
            chooseCourse = currentPorxy.addFreeCoruse(userId, coursepublish);
            currentPorxy.addCourseTabls(chooseCourse);

        } else {
            //添加收费课程
            chooseCourse = currentPorxy.addChargeCoruse(userId, coursepublish);
        }
        XcCourseTablesDto learningStatus = getLearningStatus(userId, courseId);
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
        BeanUtils.copyProperties(chooseCourse, xcChooseCourseDto);
        xcChooseCourseDto.setLearnStatus(learningStatus.getLearnStatus());
        return xcChooseCourseDto;
    }

    /**
     * 获取学习资格
     *
     * @param userId
     * @param courseId
     * @return
     */
    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {
        //课程表有无信息
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        if (xcCourseTables == null) {
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }
        BeanUtils.copyProperties(xcCourseTables, xcCourseTablesDto);
        //判断学习资格是否过期
        boolean isExpires = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        //已过期
        if (isExpires) {
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        }
        //正常学习
        xcCourseTablesDto.setLearnStatus("702001");
        return xcCourseTablesDto;
    }

    /**
     * 添加选课状态，增加收费课程表
     *
     * @param chooseCourseId
     * @return
     */
    @Override
    @Transactional
    public boolean savecChooseCourseStaus(String chooseCourseId) {
        XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectById(chooseCourseId);
        if (xcChooseCourse == null) {
            log.debug("没有这个选课,chooseCourseId:{}", chooseCourseId);
            XueChengPlusException.cast("没有这个选课");
        }
        xcChooseCourse.setStatus("701001");
        int i = xcChooseCourseMapper.updateById(xcChooseCourse);
        if (i <= 0) {
            return false;
        }
        log.debug("更新选课状态成功，xcChooseCourse:{}", xcChooseCourse.toString());
        XcCourseTables xcCourseTables = currentPorxy.addCourseTabls(xcChooseCourse);
        if (xcCourseTables == null) {
            log.debug("添加收费课程表失败，xcChooseCourse:{}", xcChooseCourse.toString());
            XueChengPlusException.cast("添加收费课程表失败");
        }
        return true;
    }

    /**
     * 我的课程表查询数据
     *
     * @param params
     * @return
     */
    @Override
    public PageResult<XcCourseTables> mycourestabls(MyCourseTableParams params) {
        //页码
        long pageNo = params.getPage();
        //每页记录数,固定为4
        long pageSize = 4;
        Page page = new Page(pageNo, pageSize);
        String userId = params.getUserId();
        LambdaQueryWrapper<XcCourseTables> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcCourseTables::getUserId, userId);
        Page pages = xcCourseTablesMapper.selectPage(page, queryWrapper);
        List records = pages.getRecords();
        long total = pages.getTotal();
        return new PageResult<XcCourseTables>(records, pageNo, pageSize, total);
    }

    /**
     * 添加收费课程选课记录
     *
     * @param userId
     * @param coursepublish
     * @return
     */
    @Transactional
    public XcChooseCourse addChargeCoruse(String userId, CoursePublish coursepublish) {
        //已选收费的、已选成功的课程，直接返回
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getStatus, "701002")//待支付,还没开始支付，这里就是待支付
                .eq(XcChooseCourse::getCourseId, coursepublish.getId())
                .eq(XcChooseCourse::getOrderType, "700002");//收费课程
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
        if (xcChooseCourses != null && xcChooseCourses.size() > 0) {
            return xcChooseCourses.get(0);
        }
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700002");//收费课程
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setStatus("701002");//待支付

        xcChooseCourse.setValidDays(coursepublish.getValidDays());
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));
        xcChooseCourseMapper.insert(xcChooseCourse);
        return xcChooseCourse;

    }

    /**
     * 添加选课记录
     *
     * @param userId
     * @param coursePublish
     * @return
     */
    @Transactional
    public XcChooseCourse addFreeCoruse(String userId, CoursePublish coursePublish) {
        //如果存在待支付交易记录直接返回
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getStatus, "701001")
                .eq(XcChooseCourse::getCourseId, coursePublish.getId())
                .eq(XcChooseCourse::getOrderType, "700001");
        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
        if (xcChooseCourses == null && xcChooseCourses.size() > 0) {
            return xcChooseCourses.get(0);
        }
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        xcChooseCourse.setCourseId(coursePublish.getId());
        xcChooseCourse.setCourseName(coursePublish.getName());
        xcChooseCourse.setStatus("701001");
        xcChooseCourse.setCoursePrice(0f);
        xcChooseCourse.setCompanyId(coursePublish.getCompanyId());
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setOrderType("700001");
        xcChooseCourse.setValidDays(coursePublish.getValidDays());
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        xcChooseCourse.setCoursePrice(coursePublish.getPrice());
        xcChooseCourse.setUserId(userId);
        xcChooseCourseMapper.insert(xcChooseCourse);
        return xcChooseCourse;
    }

    /**
     * 添加课程表
     *
     * @param xcChooseCourse
     * @return
     */
    @Transactional
    public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse) {
        Long courseId = xcChooseCourse.getCourseId();
        String userId = xcChooseCourse.getUserId();
        //课程表中是否已存在这门课
        XcCourseTables xcCourseTables = xcCourseTablesMapper.
                selectOne(new LambdaQueryWrapper<XcCourseTables>().
                        eq(XcCourseTables::getCourseId, courseId).
                        eq(XcCourseTables::getUserId, userId));
        if (xcCourseTables != null) {
            return xcCourseTables;
        }
        xcCourseTables = new XcCourseTables();
        BeanUtils.copyProperties(xcChooseCourse, xcCourseTables);
        xcCourseTables.setChooseCourseId(xcChooseCourse.getId());
        xcCourseTables.setCourseType(xcChooseCourse.getOrderType());
        xcCourseTablesMapper.insert(xcCourseTables);
        return xcCourseTables;
    }

    /**
     * 根据用户id和课程id查课程表
     *
     * @param userId
     * @param courseId
     * @return
     */
    public XcCourseTables getXcCourseTables(String userId, Long courseId) {
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>()
                .eq(XcCourseTables::getUserId, userId)
                .eq(XcCourseTables::getCourseId, courseId));
        return xcCourseTables;

    }

}
